﻿'
' Quiz Module for DotNetNuke
' Project Contributors - Will Strohl (http://www.WillStrohl.com)
'
'Copyright (c) 2011, Will Strohl
'All rights reserved.
'
'Redistribution and use in source and binary forms, with or without modification, are 
'permitted provided that the following conditions are met:
'
'Redistributions of source code must retain the above copyright notice, this list of 
'conditions and the following disclaimer.
'
'Redistributions in binary form must reproduce the above copyright notice, this list 
'of conditions and the following disclaimer in the documentation and/or other 
'materials provided with the distribution.
'
'Neither the name of Quiz Module for DotNetNuke, nor the names of its contributors may be 
'used to endorse or promote products derived from this software without specific prior 
'written permission.
'
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
'EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
'OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
'SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
'INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
'TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
'BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
'CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
'ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
'DAMAGE.
'

Imports DotNetNuke.Security
Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.UI.Skins.Skin
Imports System.Text
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports WillStrohl.Modules.Quiz.QuizController
Imports WillStrohl.Modules.Quiz.QuizInfoMembers

Namespace WillStrohl.Modules.Quiz

    Partial Public MustInherit Class EditQuestion
        Inherits WnsPortalModuleBase

#Region " Private Members "

        Private p_QuizId As Integer = Null.NullInteger
        Private p_Quiz As QuizInfo = Nothing
        Private p_QuestionId As Integer = Null.NullInteger

#End Region

#Region " Properties "

        Private ReadOnly Property QuestionId As Integer
            Get
                If p_QuestionId = Null.NullInteger Then
                    Dim obj As Object = Settings(QUESTION_ID_FIELD)
                    If Not obj Is Nothing Then
                        p_QuestionId = Integer.Parse(obj.ToString(), Globalization.NumberStyles.Integer)
                    End If
                End If

                Return p_QuestionId
            End Get
        End Property

        Private ReadOnly Property QuizId As Integer
            Get
                If p_QuizId = Null.NullInteger Then
                    Dim obj As Object = Settings(QUIZ_ID_FIELD)
                    If Not obj Is Nothing Then
                        p_QuizId = Integer.Parse(obj.ToString(), Globalization.NumberStyles.Integer)
                    End If
                End If

                Return p_QuizId
            End Get
        End Property

        Private ReadOnly Property Quiz As QuizInfo
            Get
                If p_Quiz Is Nothing Then
                    Dim ctlQuiz As New QuizController
                    p_Quiz = ctlQuiz.GetQuiz(QuizId)
                End If

                Return p_Quiz
            End Get
        End Property

#End Region

#Region " Event Handlers "

        Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try

                If Not Page.IsPostBack Then
                    Me.BindData()
                End If

            Catch exc As Exception ' Module failed to load
                ProcessModuleLoadException(Me, exc, Me.IsEditable)
            End Try
        End Sub

        Private Sub cmdCancel_Click(sender As Object, e As System.EventArgs) Handles cmdCancel.Click
            SendBackToQuestions()
        End Sub

        Private Sub cmdDelete_Click(sender As Object, e As System.EventArgs) Handles cmdDelete.Click
            DeleteQuestion()
            SendBackToQuestions()
        End Sub

        Private Sub cmdUpdate_Click(sender As Object, e As System.EventArgs) Handles cmdUpdate.Click
            If Page.IsValid Then
                SaveQuestion()
            End If
        End Sub

#End Region

#Region " Private Helper Functions "

        Private Sub BindData()

            Me.LocalizeModule()

            If Not Quiz Is Nothing Then

                Dim sb As New StringBuilder
                sb.AppendFormat("<h2>{0}</h2>", Quiz.QuizName)
                sb.AppendFormat("<p>{0}</p>", Quiz.QuizDescription)
                phQuiz.Controls.Add(New LiteralControl(sb.ToString))

            End If

            radQuestionType.Items.Add(New ListItem(GetLocalizedString("radQuestionType.Items.Radio"), "radio"))
            radQuestionType.Items.Add(New ListItem(GetLocalizedString("radQuestionType.Items.Checkbox"), "checkbox"))

            If QuestionId > Null.NullInteger Then
                Dim ctlQuiz As New QuizController
                Dim oQuestion As QuestionInfo = ctlQuiz.GetQuestion(QuestionId)

                If Not oQuestion Is Nothing AndAlso oQuestion.QuestionId > 0 Then
                    txtQuestion.Text = oQuestion.Question
                    radQuestionType.Items.FindByValue(oQuestion.QuestionType).Selected = True
                    chkRandomizeAnswers.Checked = oQuestion.RandomizeAnswers
                    chkActive.Checked = oQuestion.IsActive
                End If

                cmdDelete.Visible = True
            Else
                ' set default values
                radQuestionType.Items.FindByValue("radio").Selected = True
                chkActive.Checked = True
                cmdDelete.Visible = False
            End If

        End Sub

        Private Sub LocalizeModule()

            rfvQuestion.ErrorMessage = GetLocalizedString("rfvQuestion.ErrorMessage")
            cmdCancel.Text = GetLocalizedString("cmdCancel.Text")
            cmdDelete.Text = GetLocalizedString("cmdDelete.Text")
            cmdUpdate.Text = GetLocalizedString("cmdUpdate.Text")

        End Sub

        Private Sub SaveQuestion()

            Dim sec As New PortalSecurity
            Dim ctlQuiz As New QuizController
            Dim oQuestion As New QuestionInfo

            oQuestion.QuizId = QuizId
            oQuestion.Question = sec.InputFilter(txtQuestion.Text, PortalSecurity.FilterFlag.NoScripting)
            oQuestion.QuestionType = radQuestionType.SelectedValue
            oQuestion.RandomizeAnswers = chkRandomizeAnswers.Checked
            oQuestion.IsActive = chkActive.Checked
            oQuestion.LastModifiedBy = UserId

            If QuestionId > 0 Then
                ' update the question
                oQuestion.QuestionId = QuestionId
                ctlQuiz.UpdateQuestion(oQuestion)
                SendBackToQuestions()
            Else
                ' save the new question
                p_QuestionId = ctlQuiz.AddQuestion(oQuestion)
                SendToAnswers()
            End If

        End Sub

        Private Sub DeleteQuestion()

            Dim ctlQuiz As New QuizController
            ctlQuiz.DeleteQuestion(QuestionId)

        End Sub

        Private Sub SendBackToQuestions()
            Response.Redirect(EditUrl(String.Empty, String.Empty, "Questions", String.Format("{0}={1}", QUERYSTRING_QUIZ_ID_KEY, QuizId)))
        End Sub

        Private Sub SendToAnswers()
            Response.Redirect(EditUrl(String.Empty, String.Empty, "Answers", String.Format("{0}={1}", QUERYSTRING_QUESTION_ID_KEY, QuestionId)))
        End Sub

        Private Sub HandleException(ByVal exc As Exception)
            LogException(exc)
            If Me.UserInfo.IsSuperUser Or Me.UserInfo.UserID = PortalSettings.AdministratorId Then
                AddModuleMessage(Me, _
                    String.Concat(exc.Message, "<br />", exc.StackTrace), _
                    Skins.Controls.ModuleMessage.ModuleMessageType.RedError)
            Else
                AddModuleMessage(Me, exc.Message, _
                    Skins.Controls.ModuleMessage.ModuleMessageType.RedError)
            End If
        End Sub

#End Region

    End Class

End Namespace